package net.ibizsys.eclipse.studio.data;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.ibizsys.eclipse.studio.Activator;
import net.ibizsys.eclipse.studio.console.Console;
import net.ibizsys.eclipse.studio.util.FileKit;
import net.ibizsys.eclipse.studio.util.StringKit;

import org.eclipse.equinox.security.storage.ISecurePreferences;
import org.eclipse.equinox.security.storage.SecurePreferencesFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * 本地数据管理对象
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public class LocalDataManager
{

	public static final String UserNode = "net.ibizsys.eclipse.studio.data.user";

	public static final String SystemsNode = "net.ibizsys.eclipse.studio.data.systems.%1$s";

	public static final String NodeRealData = "___RealData___";

	private static LocalDataManager _ins = new LocalDataManager();

	private static boolean bInited = false;

	private File dataPath;
	private Map<String, IBizSystem> systemMap = new HashMap<String, IBizSystem>();

	public static LocalDataManager manager()
	{
		if (!bInited)
		{
			_ins.init();
			bInited = true;
		}
		return _ins;
	}

	/**
	 * 初始化
	 */
	protected void init()
	{
		String rootPath = Activator.getDefault().getRootPath() + File.separator + ".metadata" + File.separator + ".plugins" + File.separator + Activator.BUNDLE;
		dataPath = new File(rootPath);

		if (!dataPath.exists())
		{
			dataPath.mkdirs();
		}

		for (File file : dataPath.listFiles())
		{
			if (file.isFile())
			{
				if (file.canRead())
				{
					String content = null;
					try
					{
						content = FileKit.readFile(file);
						
						if (!StringKit.IsBlank(content))
						{
							try
							{
								JSONObject json = JSONObject.parseObject(content);

								IBizSystem system = new IBizSystem(json);
								systemMap.put(system.getId(), system);
								
							} catch (Exception ex)
							{
								Console.println("解析json数据异常.");
								Console.println(content);
								Console.println(ex.getMessage());
							}
						}
					} catch (Exception ex)
					{
						Console.println("无法读取数据文件[" + file.getAbsolutePath() + "].");
						Console.println(ex.getMessage());
					}
				} else
				{
					Console.println("没有读取权限，文件[" + file.getAbsolutePath() + "].");
				}
			}
		}
	}

	/**
	 * 保存用户信息
	 * 
	 * @param user 用户信息
	 */
	public void saveUser(IBizUser user)
	{
		try
		{
			ISecurePreferences node = SecurePreferencesFactory.getDefault().node(UserNode);

			if (node != null)
			{
				node.put("USERID", user.getUserId(), true);
				node.put("ACCOUNT", user.getAccount(), true);
				node.put("NAME", user.getName(), true);
				node.put("PASSWORD", user.getPassword(), true);
				node.put("TOKEN", user.getToken(), true);
				node.put("SVNACCOUNT", user.getSvnAccount(), true);
				node.put("SVNPASSWORD", user.getSvnPassword(), true);
				node.put("REMOTEURL", user.getRemoteUrl(), true);
			}
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	/**
	 * 删除用户信息
	 */
	public void removeUser()
	{
		try
		{
			ISecurePreferences node = SecurePreferencesFactory.getDefault().node(UserNode);

			if (node != null)
			{
				node.remove("USERID");
				node.remove("NAME");
				node.remove("PASSWORD");
				node.remove("TOKEN");
				node.remove("SVNACCOUNT");
				node.remove("SVNPASSWORD");
			}
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	/**
	 * 获取用户信息
	 * 
	 * @return
	 */
	public IBizUser getUser()
	{
		IBizUser user = new IBizUser();
		try
		{
			ISecurePreferences node = SecurePreferencesFactory.getDefault().node(UserNode);

			if (node != null)
			{
				user.setUserId(node.get("USERID", ""));
				user.setAccount(node.get("ACCOUNT", ""));
				user.setName(node.get("NAME", ""));
				user.setPassword(node.get("PASSWORD", ""));
				user.setToken(node.get("TOKEN", ""));
				user.setSvnAccount(node.get("SVNACCOUNT", ""));
				user.setSvnPassword(node.get("SVNPASSWORD", ""));
				user.setRemoteUrl(node.get("REMOTEURL", ""));
			}
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}

		return user;
	}

	/**
	 * 删除系统
	 * 
	 * @param systemName 系统名称
	 * @return
	 */
	public boolean removeSystem(String systemName)
	{
		try
		{
			IBizSystem system = getSystem(systemName);

			if (system != null)
			{
				systemMap.remove(system.getId());

				File file = new File(dataPath, system.getId() + ".json");
				file.delete();
			}
			return true;
		} catch (Exception ex)
		{
			Console.println("删除系统[" + systemName + "]数据文件失败.");
		}

		return false;
	}

	/**
	 * 获取[系统]数据
	 * 
	 * @param systemName 系统名称
	 * @return
	 */
	public IBizSystem getSystem(String systemName)
	{
		for (IBizSystem system : systemMap.values())
		{
			if (StringKit.IsEqual(systemName, system.getCodename(), true))
			{
				return system;
			} else
			{
				for (Project project : system.getProjects())
				{
					if (StringKit.IsEqual(systemName, project.getAppname(), true))
					{
						return system;
					}
				}
			}
		}
		return null;
	}

	/**
	 * 保存[系统]数据
	 * 
	 * @param system 系统
	 * @return
	 */
	public boolean saveSystem(IBizSystem system)
	{
		boolean result = FileKit.mkfile(new File(dataPath, system.getId() + ".json"), system.getData().toJSONString());

		if (result)
		{
			systemMap.put(system.getId(), system);
			return true;
		}

		return false;
	}

	/**
	 * 列举本地保存的系统
	 * 
	 * @param existOnDisk 是否已经检出到本地
	 * @return
	 */
	public List<IBizSystem> listLocalSystems(boolean existOnDisk)
	{
		List<IBizSystem> list = new ArrayList<IBizSystem>();

		if (systemMap.size() == 0)
		{
			Console.println("本地系统数据为空.");
			this.init();
		}

		for (IBizSystem system : systemMap.values())
		{
			if (existOnDisk)
			{
				File file = new File(Activator.getDefault().getRootPath() + File.separator + system.getCodename());

				if (file.exists())
				{
					list.add(system);
				} else
				{
					for (Project project : system.getProjects())
					{
						File file2 = new File(Activator.getDefault().getRootPath() + File.separator + project.getName());

						if (file2.exists())
						{
							list.add(system);
							break;
						}
						File file3 = new File(Activator.getDefault().getRootPath() + File.separator + project.getAppname());

						if (file3.exists())
						{
							list.add(system);
							break;
						}
					}
				}
			} else
			{
				list.add(system);
			}
		}

		return list;
	}
}
